package com.cskaoyan.user.controller;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.commons.result.UserInfo;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dto.UserLoginDto;
import com.cskaoyan.user.dto.UserLoginResponse;
import com.cskaoyan.user.form.KaptchaCodeRequest;
import com.cskaoyan.user.form.UserLoginRequest;
import com.cskaoyan.user.service.IKaptchaService;
import com.cskaoyan.user.service.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author tan
 * @date 2023年01月10日 10:10
 */
@RestController
@RequestMapping("/user")
public class LoginController {
    @Autowired
    private IKaptchaService iKaptchaService;

    @Autowired
    private ILoginService iLoginService;

    private static String ACCESS_TOKEN = "access_token";

    @PostMapping("/login")
    public ResponseData login(@RequestBody Map map, HttpServletRequest request, HttpServletResponse response) {
        String userName = (String) map.get("userName");
        String userPwd = (String) map.get("userPwd");
        String captcha = (String) map.get("captcha");
        UserLoginRequest userLoginRequest = new UserLoginRequest(userName, userPwd, captcha);
        // 校验验证码
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(uuid);
        kaptchaCodeRequest.setCode(captcha);
        try {
            iKaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        } catch (Exception e) {
            return new ResponseUtil<>().setErrorMsg(UserRetCode.KAPTCHA_CODE_ERROR.getMessage());
        }

        ResponseData responseData = iLoginService.login(userLoginRequest);

        UserLoginResponse userLoginResponse = (UserLoginResponse) responseData.getResult();
        String token = userLoginResponse.getToken();
        Cookie cookie = new Cookie(ACCESS_TOKEN, token);
        cookie.setPath("/");
        CookieUtil.setCookie(response, cookie);

        return responseData;
    }

    @GetMapping("login")
    public ResponseData login(HttpServletRequest request) {
        String userInfo = request.getHeader("user_info");
        UserInfo user = JSON.parseObject(userInfo, UserInfo.class);
        Long uid = user.getUid();
        String file = iLoginService.getMemberFile(uid);
        UserLoginDto userLoginDto = new UserLoginDto(uid, file);
        return new  ResponseUtil<>().setData(userLoginDto);
    }
}
